package com.ideafactory.client.views;

import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.IOException;

/**
 * Created by LiuShao on 2016/6/28.
 */
public class CameraView extends SurfaceView implements SurfaceHolder.Callback {

    private Camera mCamera;// Camera对象
    private Context context;
    private boolean isPreviewing = false;//是否正在预览

    public CameraView(Context context) {
        this(context, null);
    }

    public CameraView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        holder = getHolder();
        holder.addCallback(this);
    }

    private SurfaceHolder holder;// SurfaceView的控制器

    private static final String TAG = "CameraView";

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Log.d(TAG, "surfaceCreated: ");
        if (checkCameraHardware()) {
            try {
                mCamera = Camera.open();//打开前置摄像头
                startCamera();
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    mCamera = Camera.open(1);//打开前置摄像头
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    private void startCamera() {
        if (mCamera == null) {
        } else {
            try {
                mCamera.setPreviewDisplay(holder);//设置显示面板控制器
                mCamera.startPreview();//开始预览，这步操作很重要
                isPreviewing = true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Log.d(TAG, "surfaceChanged: ");
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.d(TAG, "surfaceDestroyed: ");
        if (mCamera != null) {
            try {
                /* 停止预览 */
                mCamera.setPreviewCallback(null);
                mCamera.stopPreview();
                isPreviewing = false;
                mCamera.release();
                mCamera = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 检测摄像头是否存在的私有方法
    private boolean checkCameraHardware() {
        if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            // 摄像头存在
            return true;
        } else {
            // 摄像头不存在
            return false;
        }
    }
}
